package com.yalu.read.excel.sale;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.yalu.entity.SaleData;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class SaleFiveExcelRead {

    /**
     * 测试pdf文件的创建
     *
     * @param args
     */
    public static void main(String[] args) {
        String filePath = "D://yalu//sale//";  //这里先手动把绝对路径的文件夹给补上。
        List<String> filePaths = new ArrayList<>();
        recursionFile(filePath, filePaths);
        List<SaleData> list = new ArrayList<>();
        SaleFiveExcelRead pdfUtil = new SaleFiveExcelRead();
        for (String fileName : filePaths) {
            pdfUtil.readExcel(fileName, list);
        }
        System.out.println("文件数量：" + filePaths.size()+" 数据数量: "+list.size());
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String outFileName = "D:\\yalu\\销售单_" + LocalDateTime.now().format(dtf) + ".xlsx";
        writerFils(list, outFileName);
    }

    /**
     * 读PDF文件，使用了pdfbox开源项目
     *
     * @param fileName
     */
    public static void readExcel(String fileName, List<SaleData> list) {
        File file = new File(fileName);
        FileInputStream in = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(fileName);
            List<Object> dataList = EasyExcelFactory.read(inputStream, new Sheet(1, 0));
            int size = dataList.size();
            Queue<SaleData> dataQueue = new LinkedList<>();
            boolean isOk = true;
            for (int i = 0; i < size; i++) {
                SaleData dataNow = dataQueue.poll();
                SaleData saleData = new SaleData();
                if (null != dataNow) {
                    BeanUtils.copyProperties(dataNow,saleData);
                }
                List<String> lineList = (List<String>) dataList.get(i);
                String lineText = JSON.toJSONString(lineList);
                if (StringUtils.hasText(lineText) && lineText.toLowerCase().contains("invoice no:")) {
                    String no = lineList.get(8).toLowerCase();;
                    saleData.setSaleNo(no.replace("invoice no:","").trim());
                }if (StringUtils.hasText(lineText) && lineText.toLowerCase().contains("date")&& !lineText.toLowerCase().contains("on board date:")) {
                    String no = lineList.get(8).toLowerCase();;
                    saleData.setDate(no.replace("date","").trim());
                } else if (StringUtils.hasText(lineText) && lineText.toLowerCase().contains("total:")) {
                    saleData.setAmount(lineList.get(8));
                }
                dataQueue.offer(saleData);
                if (StringUtils.hasText(saleData.getAmount()) && StringUtils.hasText(saleData.getDate())) {
                    SaleData data = dataQueue.poll();
                    data.setFileName(fileName);
                    list.add(data);
                    isOk = false;
                    break;
                }
            }
            if(isOk){
                System.out.printf("未处理文件:"+fileName);
            }
        } catch (Exception e) {
            System.out.println("读取PDF文件" + file.getAbsolutePath() + "生失败！" + e);
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    private static boolean isNull(String str){
        boolean isNull = false;
        if(StringUtils.hasText(str)){
            if(!"null".equals(str)&&!"[null".equals(str)&&!"null]".equals(str)){
                isNull = true;
            }
        }
        return isNull;
    }

    /**
     * 写入文件
     *
     * @param data
     * @param outFileName
     */
    public static void writerFils(List<SaleData> data, String outFileName) {
        try {
            ExcelWriter excelWriter = EasyExcel.write(outFileName, SaleData.class).build();
            String sheetName = "1";
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            excelWriter.write(data, writeSheet);
            // 千万别忘记finish 会帮忙关闭流
            excelWriter.finish();
        } catch (Exception e) {
            System.out.println("文件写入失败：" + e.getMessage());
        }
    }

    /**
     * 递归文件
     *
     * @param path
     * @param filePaths
     */
    public static void recursionFile(String path, List<String> filePaths) {
        if (StringUtils.hasText(path)) {
            File file = new File(path);
            for (File f : file.listFiles()) {
                if (f.isDirectory()) {
                    recursionFile(f.getPath(), filePaths);
                } else {
                    if (f.getPath().toLowerCase().contains(".xls")||f.getPath().toLowerCase().contains(".xlsx")) {
                        filePaths.add(f.getPath());
                    }
                }
            }
        }
    }
}
